#include "I_BaseLib.h"

using namespace std;

SO_MANAGER::SO_MANAGER()
{
	mousedown = false;
	mousex_whendown = 0;
	mousey_whendown = 0;
	posx_whendown = 0;
	posy_whendown = 0;
}

SO_MANAGER::~SO_MANAGER(void)
{
	ObjectList.~vector();
}

void SO_MANAGER::NewObject()
{
	int Pieces = (int)ObjectList.size();
	ScreenObject* SO = new ScreenObject(0,Pieces*110);
	ObjectList.push_back(SO);
}

void SO_MANAGER::NewObject(const wchar_t* bitmap_name)
{
	ScreenObject* SO = new ScreenObject(bitmap_name);
	ObjectList.push_back(SO);
}

void SO_MANAGER::Connect(ScreenObject* SO1, ScreenObject* SO2)
{
	
	SO1->AddConnection (SO2);

}

void SO_MANAGER::Render(BASE_RENDERER* pRenderer)
{
	for (std::vector<ScreenObject*>::size_type i = 0; i < ObjectList.size(); i++)
	{
		ObjectList[i]->Render(pRenderer);
		ObjectList[i]->RenderConnections(pRenderer,COLOR(0xff,0x00,0x00));
	}
}

void SO_MANAGER::OnMouseDown(MESSAGE_HANDLER* pMessageHandler, int x, int y)
{
	mousedown = true;
	mousex_whendown = x;
	mousey_whendown = y;

	if (ObjectList.size()>0)
	{
		for (int i = (int) ObjectList.size()-1; i >= 0; i--)
		{
			if (ObjectList[i]->HitBox(x,y)) 
			{
				ObjectList[i]->Select();
				posx_whendown = ObjectList[i]->GetPosX();
				posy_whendown = ObjectList[i]->GetPosY();
				pMessageHandler->AsyncronMessage(PAINT);
				return;
			}
		}
	}
}

void SO_MANAGER::OnMouseUp(MESSAGE_HANDLER* pMessageHandler, int x, int y)
{
	for (int i=0; i < (int) ObjectList.size(); i++)
	{
		ObjectList[i]->UnSelect();
	}
	mousedown = false;
	pMessageHandler->AsyncronMessage(PAINT);
}


void SO_MANAGER::OnMouseMove(MESSAGE_HANDLER* pMessageHandler,int cur_x, int cur_y)
{
	if (mousedown)
	{
		for (std::vector<ScreenObject*>::size_type i=0; i < ObjectList.size();i++)
		{
			if (ObjectList[i]->IsSelected()) 
			{
				ObjectList[i]->SetPos( posx_whendown + cur_x - mousex_whendown, posy_whendown + cur_y - mousey_whendown );
				pMessageHandler->AsyncronMessage(PAINT);
				return;
			}
		}

	}

}
